package com.leyou.auth.service.impl;

import com.leyou.auth.client.UserClient;
import com.leyou.auth.entity.UserInfo;
import com.leyou.auth.properties.JwtProperties;
import com.leyou.auth.service.AuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.enums.LyExceptionEnums;
import com.leyou.common.exception.LyException;
import com.leyou.user.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

/**
 * @author linzx
 * @date 2020/3/29
 */
@Service
@Slf4j
@EnableConfigurationProperties(JwtProperties.class)
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UserClient userClient;
    @Autowired
    private JwtProperties jwtProps ;

    @Override
    public String login(String username, String password) {
        try {
        User user = userClient.login(username, password);
        if (user == null) {
            throw new LyException(LyExceptionEnums.INVALID_USERNAME_PASSWORD) ;
        }
            String token = JwtUtils.generateToken(new UserInfo(user.getId(), username), jwtProps.getPrivateKey(), jwtProps.getExpire());
            return token;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("[授权中心] 生成token失败,用户名或密码有误,用户名称:{}" , username,e);
            throw new LyException(LyExceptionEnums.CREATE_TOKEN_ERROR);
        }
    }

    @Override
    public UserInfo verify(String token) {
        if (StringUtils.isBlank(token)) {
            throw new LyException(LyExceptionEnums.NO_AUTHORIZED) ;
        }
        try {
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, jwtProps.getPublicKey());
            return userInfo;
        } catch (Exception e) {
            e.printStackTrace();
            throw new LyException(LyExceptionEnums.NO_AUTHORIZED) ;
        }
    }
}
